//
//  ViewController.m
//  第一个ios程序
//
//  Created by mir_yan on 2018/10/1.
//  Copyright © 2018年 hakeem. All rights reserved.
//

#import "ViewController.h"
#define REDVIEWTAG 10
#define BLUEVIEWTAG 11

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 在父视图 添加子视图
    UIView* superView = self.view;
    
    UIView* redView = [[UIView alloc] initWithFrame:CGRectMake(60, 60, 250, 250)];
    [redView setBackgroundColor:[UIColor redColor]];
    redView.tag = 10;
    
    [superView addSubview:redView];
    
    // 父视图获取子视图
    UIView* superView1 = self.view;
    
    UIView* blueView = [[UIView alloc] initWithFrame:CGRectMake(70, 70, 250, 250)];
    [blueView setBackgroundColor:[UIColor blueColor]];
    blueView.tag = 11;
    
    [superView1 addSubview:blueView];
    
    // 获取父视图的所有子视图
    // 有隐藏视图对象
    NSArray* subViews = [superView subviews];
    for (UIView* subView in subViews) {
        // 先识别 子视图对象
        if ([subView isMemberOfClass:[UILabel class]]) {
          NSLog(@"view.tag = %ld", subView.tag);
        }
    }
    
//    移除子视图
//    [redView removeFromSuperview];
    // 移动
//    [superView bringSubviewToFront:redView];
//    [superView sendSubviewToBack:blueView];
    
    UIView* greenView = [[UIView alloc] initWithFrame:CGRectMake(80, 80, 250, 250)];
    [greenView setBackgroundColor:[UIColor greenColor]];
    [superView addSubview:greenView];
    
    NSInteger redIndex = [superView.subviews indexOfObject:redView];
    NSInteger greenIndex = [superView.subviews indexOfObject:greenView];

    // 交互两个子视图的位置 不是 frame
    [superView exchangeSubviewAtIndex:redIndex withSubviewAtIndex:greenIndex];
    
    // 让数组的对象执行@selector 内指定的方法
    [superView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 定时器
//    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction {
//    static NSInteger i = 0;
//    NSLog(@"%ld", i++);
    UIView* redView = [self.view viewWithTag:10];
    CGRect frame = redView.frame;
    
    static NSInteger X = 1;
    static NSInteger Y = 1;
    
    CGFloat right = [UIScreen mainScreen].bounds.size.width;
    CGFloat bottom = [UIScreen mainScreen].bounds.size.height;
    
    if (frame.origin.x < 0 || frame.origin.x + frame.size.width >= right) {
        X *= -1;
    }
    if (frame.origin.y < 0 || frame.origin.y + frame.size.height >= bottom) {
        Y *= -1;
    }
    frame.origin.x = X;
    frame.origin.y = Y;
    
    redView.frame = frame;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
